﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.SessionState;
using ServiceStack.Redis;
using RedisSessionStore.Configuration;
using RedisSessionStore.Redis;

namespace RedisSessionStore.NoLock
{
	public class RedisNoLockSessionStateItemsCollection : RedisSessionConfig, ISessionStateItemCollection
	{
		private String _id;
		private Int32 _timeout;
		private String _redisServer;
		private Int32 _redisDb;

		private bool _isDirty;

		public RedisNoLockSessionStateItemsCollection(string id, int timeout, string redisServer, int redisDb)
		{
			_id = id;
			_timeout = timeout;
			_redisServer = redisServer;
			_redisDb = redisDb;

			_isDirty = false;
		}

		#region ISessionStateItemCollection Members
		public void Clear() { }

		public bool Dirty
		{
			get { return _isDirty; }
			set { _isDirty = value; }
		}

		public System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		public void Remove(string name)
		{
			string key = GetKey(name);
			using (var redis = SingleRedisPool.GetClient(_redisServer))
			{
				redis.Remove(name);
			}
		}

		public void RemoveAt(int index)
		{
			throw new NotImplementedException("Please use Remove(string name) instead");
		}

		public object this[int index]
		{
			get
			{
				throw new NotImplementedException("Please use Session[string] instead");
			}
			set
			{
				throw new NotImplementedException("Please use Session[string] instead");
			}
		}

		public object this[string name]
		{
			get
			{
				string key = GetKey(name);
				using (var redis = SingleRedisPool.GetClient(_redisServer))
				{
					return redis.Get<object>(key);
				}
			}
			set
			{
				string key = GetKey(name);
				using (var redis = SingleRedisPool.GetClient(_redisServer))
				{
					bool result = redis.Set<object>(key, value);
				}
			}
		}

		#endregion

		#region ICollection Members

		public void CopyTo(Array array, int index)
		{
			throw new NotImplementedException();
		}

		public int Count
		{
			get { throw new NotImplementedException(); }
		}

		public bool IsSynchronized
		{
			get { throw new NotImplementedException(); }
		}

		public object SyncRoot
		{
			get { throw new NotImplementedException(); }
		}

		#endregion

		#region IEnumerable Members

		public System.Collections.IEnumerator GetEnumerator()
		{
			throw new NotImplementedException();
		}

		#endregion

		#region Utility
		protected string GetKey(string key)
		{
			return "Session_" + _id + "_" + key;
		}
		#endregion
	}
}
